import { createStore } from "vuex"
import { CHANGE_INFO } from "./mutation_types"

import homeModule from './modules/home'
import counterModule from './modules/counter'

const store = createStore({
  // state: 状态
  state: {
    // counter: 0,
    rootCounter: 100,

    name: "mapState-name",
    level: 100,
    friends: [
      { id: 111, name: "getter-name1", age: 20 },
      { id: 112, name: "getter-name2", age: 30 },
      { id: 113, name: "getter-name3", age: 25 }
    ],
  },
  // mutaions: 同步方法
  mutations: {
    increment(state) {
      state.counter++
    },
    changeName(state, payload) {
      state.name = payload
    },
    incrementLevel(state) {
      state.level++
    },
    [CHANGE_INFO](state, payload) {
      state.name = payload.name,
      state.level = payload.level

      // 重要的原则: 不要在mutation方法中执行异步操作
      // fetch("xxxx").then(res => {
      //   res.json().then(res => {
      //     state.name = res.name
      //   })
      // })
    },

    // changeBanners(state, banners) {
    //   state.banners = banners
    // },
    // changeRecommends(state, recommends) {
    //   state.recommends = recommends
    // }
  },
  // actions: 异步方法
  actions: {
    incrementAction(context) {
      context.commit("increment")
    },
    changeNameAction({ commit }, payload) {
      commit("changeName", payload)
    },
  },
  // getters: 计算属性
  getters: {
    doubleCounter(state) {
      return state.counter * 2
    },
    totalAge(state) {
      return state.level + 100
    },
    message(state) {
      return `name: ${state.name}, level: ${state.level}`
    },
    getFriendById(state) {
      return (id) => {
        return state.friends.find((item) => item.id === id)
      }
    }
  },
  // modules: 模块
  modules: {
    home: homeModule,
    count: counterModule
  }
})

export default store